package org.zjt.rxjava.lession.second;

import io.reactivex.Observable;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 *
 *      1、publish connect
 *
 *      RefCount: 跟踪有多少个观察者订阅它，直到最后一个观察者完成才断开与下层可连接Observable的连接。
 *
 *
 * @author juntao.zhang
 * Date: 2018-06-28 下午8:46
 * @see
 */
public class Chapter5 {

    public static void main(String[] args) throws InterruptedException {
        Random random = new Random();
        Observable<Integer> threeRandoms = Observable.range(1,3)
                .map(i -> random.nextInt())
                .publish()
                .autoConnect(2);

        //Observer 1 - print each random integer
        threeRandoms.subscribe(i -> System.out.println("Observer 1: " + i));
        threeRandoms.subscribe(i -> System.out.println("Observer 2: " + i));


        Observable<Long> seconds =
                Observable.interval(1, TimeUnit.SECONDS)
                        .publish()
                        .autoConnect();
        //Observer 1
        seconds.subscribe(i -> System.out.println("Observer 1: "+ i));


        //Observer 2
        seconds.subscribe(i -> System.out.println("Observer 2: " + i));


        Observable<Long> seconds1 =
                Observable.interval(1, TimeUnit.SECONDS)
                        .replay()
                        .autoConnect();

        seconds1.subscribe(i -> System.out.println("Observer 3: " + i));
        seconds1.subscribe(i -> System.out.println("Observer 4: " + i));

        TimeUnit.SECONDS.sleep(3);

    }
}
